$(function () {
	// 点击保存,提交数据
	$('#addForm').on('submit', function (e) {
		e.preventDefault()
		var date = $('#addForm').serialize()
		$.ajax({
			url: 'http://localhost:3000/posts',
			type: 'post',
			data: date,
			success: function (res) {
				// console.log(res)
				location.href = '/admin/posts.html'

			}
		})
	})

	// 获取文章分类
	$.ajax({
		type: 'get',
		url: 'http://localhost:3000/categories',
		success: function (res) {
			// console.log(res)
			var str = template('categoryTpl', { data: res })
			$('#category').html(str)

		}
	})

	// 上传文件
	$('#feature').on('change', function () {
		var file = this.files[0]
		var formData = new FormData()
		formData.append('cover', file)
		$.ajax({
			type: 'post',
			url: 'http://39.101.191.123:3000/upload',
			data: formData,
			// 告诉$.ajax方法不要处理data属性对应的参数
			processData: false,
			// 告诉$.ajax方法不要设置参数类型
			contentType: false,
			success: function (res) {
				console.log(res)
				$('#thumbnail').val(res[0].cover);

			}
		})
	})

	// 修改文章  获取id
	function getId() {
		var urls = location.search
		if (urls.length == 0) {
			return false
		}
		// console.log(urls)
		var idChange = urls.split('?')[1].split('=')[1]
		return idChange
	}
	var id = getId()
	console.log(id)//5f38ea333565df1ce8f5866f
	// 获取要修改文章请求
	if (id) {
		$.ajax({
			type: 'get',
			url: 'http://localhost:3000/posts/' + id,
			success: function (res) {
				console.log(res)
				$.ajax({
					url: '/categories',
					type: 'get',
					success: function (response) {
						res.categories = response
						var html = template('modifyTpl', res);
						$('#parentBox').html(html);
					}
				})
			}
		})
	}


	// 当数据表单提交时
	$('#parentBox').on('submit', '#modifyForm', function (e) {
		e.preventDefault()
		var date = $(this).serialize()
		var id = $(this).attr('data-id')
		$.ajax({
			url: 'http://localhost:3000/posts/' + id,
			type: 'put',
			data: date,
			success: function (res) {
				location.href = '/admin/posts.html'
			}
		})
	})
})